import 'package:flutter/material.dart';
import '../models/product.dart';
import '../services/api_service.dart';

class ProductsProvider extends ChangeNotifier {
  final ApiService _api = ApiService();

  final List<Product> _items = [];
  List<Product> get items => List.unmodifiable(_items);

  bool isLoading = false;
  bool isRefreshing = false;
  bool hasMore = true;
  String? errorMessage;

  String? query;
  String? category;

  int _limit = 20;
  int _skip = 0;

  List<String> categories = [];
  bool categoriesLoading = false;
  String? categoriesError;

  Future<void> loadCategories() async {
    if (categories.isNotEmpty) return;
    categoriesLoading = true;
    categoriesError = null;
    notifyListeners();
    try {
      categories = await _api.fetchCategories();
    } catch (e) {
      categoriesError = e.toString();
    } finally {
      categoriesLoading = false;
      notifyListeners();
    }
  }

  Future<void> refresh() async {
    isRefreshing = true;
    errorMessage = null;
    _skip = 0;
    hasMore = true;
    notifyListeners();
    try {
      final page = await _api.getProducts(query: query, category: category, limit: _limit, skip: _skip);
      _items
        ..clear()
        ..addAll(page.products);
      _skip = page.skip + page.limit;
      hasMore = page.hasMore;
    } catch (e) {
      errorMessage = e.toString();
    } finally {
      isRefreshing = false;
      notifyListeners();
    }
  }

  Future<void> loadMore() async {
    if (!hasMore || isLoading) return;
    isLoading = true;
    errorMessage = null;
    notifyListeners();
    try {
      final page = await _api.getProducts(query: query, category: category, limit: _limit, skip: _skip);
      _items.addAll(page.products);
      _skip = page.skip + page.limit;
      hasMore = page.hasMore;
    } catch (e) {
      errorMessage = e.toString();
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  void setQuery(String? q) {
    query = (q == null || q.isEmpty) ? null : q;
  }

  void setCategory(String? c) {
    category = (c == null || c.isEmpty) ? null : c;
  }

  void clearFilters() {
    query = null;
    category = null;
  }
}